package org.jeecg.modules.system.Device;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhyd.oauth.log.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.hibernate.internal.build.AllowSysOut;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.bicycle.order.entity.BikeVehicleOrder;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.mapper.BikeVehicleMapper;
import org.jeecg.modules.common.service.CommonMethodService;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.controller.LockSocket;
import org.jeecg.modules.controller.UserWebSocket;
import org.jeecg.modules.param.maintain.entity.BikePileLock;
import org.jeecg.modules.param.maintain.mapper.BikePileLockMapper;
import org.jeecg.modules.param.member.entity.BikeMemberUser;
import org.jeecg.modules.param.member.entity.BikeMemberUserCard;
import org.jeecg.modules.param.member.mapper.BikeMemberUserCardMapper;
import org.jeecg.modules.param.member.mapper.BikeMemberUserMapper;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.param.spend.entity.BikeMemberUserSpend;
import org.jeecg.modules.param.spend.mapper.BikeMemberUserSpendMapper;
import org.jeecg.modules.param.staffUser.entity.LoginRes;
import org.jeecg.modules.param.staffUser.mapper.StaffMapper;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.system.Device.vo.SwitchLockRspRes;
import org.jeecg.modules.utils.CostUtils;
import org.jeecg.modules.utils.RandomCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 月月鸟
 */
@Component
public class DeviceMethod {
    @Resource
    private BikePileMapper bikePileMapper;
    @Resource
    private BikeStationMapper bikeStationMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private BikeVehicleOrderMapper bikeVehicleOrderMapper;
    @Resource
    private BikeMemberUserMapper bikeMemberUserMapper;
    @Resource
    private BikeVehicleMapper bikeVehicleMapper;
    @Resource
    private LockSocket lockSocket;
    @Resource
    private UserWebSocket userWebSocket;
    @Resource
    private BikeMemberUserCardMapper bikeMemberUserCardMapper;
    @Resource
    private BikePileLockMapper bikePileLockMapper;
    @Resource
    private BikeMemberUserSpendMapper bikeMemberUserSpendMapper;
    @Autowired
    private CommonMethodService commonMethodService;
    /**
     * 还车关锁上传
     *  return   上传结果0：数据校验失败1：成功
     * */
    @Transactional(rollbackFor = Exception.class)
    public void lockRecord(String stationCode, String pileCode, String vehicleCode, Date lockTime) {
        try {
            //获取还车网点信息
            BikeStation bikeStation = this.getStation(stationCode);
            //获取还车车桩信息
            BikePile bikePile=this.getBikePile(bikeStation,pileCode);
            //车辆信息
            BikeVehicle vehicle = this.getVehicleByCode(vehicleCode);
            //订单信息
            BikeVehicleOrder vehicleOrder = this.getOrderByBikeId(vehicle.getId());
            //1.修改车桩信息
            bikePile.setLockStatus("0");
            bikePileMapper.updateById(bikePile);
            //2.修改车辆信息
            vehicle.setStatus(BikeConstant.bike_status_pile);
            vehicle.setPileId(bikePile.getId());
            bikeVehicleMapper.updateById(vehicle);
            if(vehicleOrder == null){
                //3.管理员开关锁记录
                BikePileLock pileLock = this.adminOrderByBikeId(vehicle.getId());
                if (pileLock != null){
                    //2.1 未还车或者还车数据还未上来,更新管理员开锁记录
                    pileLock.setParkTime(lockTime);
                    pileLock.setParkPile(bikePile.getId());
                    long second = CostUtils.getSecond(pileLock.getPickTime().getTime(), lockTime.getTime());
                    pileLock.setUseLong((int) second);
                    bikePileLockMapper.updateById(pileLock);
                    this.lockSocketOpenYN(BikeConstant.y_n_yes,bikeStation.getCode(),bikePile.getCode(),bikePile.getCheckCode(),pileLock.getPickUser(),4);
                } else {
                    // 已还车，且还车数据先上来,增加管理员开锁记录
                    pileLock = new BikePileLock();
                    pileLock.setCode(RandomCodeUtils.getRandomCode("LK"));
                    pileLock.setParkPile(bikePile.getId());
                    pileLock.setParkTime(lockTime);
                    pileLock.setVehicleId(vehicle.getId());
                    pileLock.setVehicleStatus("2");
                    bikePileLockMapper.insert(pileLock);
                }
            } else {
                //3.修改借车记录
                if (vehicleOrder.getStopTime()==null){
                    if (lockTime.getTime()-vehicleOrder.getPickTime().getTime()<0){
                        vehicleOrder.setStopTime(new Date());
                    }else {
                        vehicleOrder.setStopTime(lockTime);
                    }

                }
                if (vehicleOrder.getParkTime()==null){
                    if (lockTime.getTime()-vehicleOrder.getPickTime().getTime()<0){
                        vehicleOrder.setParkTime(new Date());
                    }else {
                        vehicleOrder.setParkTime(lockTime);
                    }
                }
                vehicleOrder.setParkPile(bikePile.getId());
                if (StringUtils.isEmpty(vehicleOrder.getParkType())){
                    vehicleOrder.setParkType("1");
                }
                if (StringUtils.isEmpty(vehicleOrder.getParkUser())){
                    vehicleOrder.setParkUser(vehicleOrder.getPickUser());
                }
                //秒
                long useTime = CostUtils.getSecond(vehicleOrder.getPickTime().getTime(), vehicleOrder.getStopTime().getTime());
                vehicleOrder.setUseLong((int) useTime);
                BikeMemberUser memberUser = bikeMemberUserMapper.selectById(vehicleOrder.getPickUser());

                BigDecimal bigDecimal = new BigDecimal(commonMethodService.getCost(vehicleOrder.getPickTime(), vehicleOrder.getStopTime()));
                if (StringUtils.isNotEmpty(vehicleOrder.getIsPay())){
                    if (!vehicleOrder.getIsPay().equals(BikeConstant.y_n_yes)){
                        //判断金额
                        if (bigDecimal.compareTo(new BigDecimal(0))==0){
                            //应付0元
                            vehicleOrder.setRideStatus("5");
                            vehicleOrder.setPayActual(bigDecimal);
                            vehicleOrder.setIsPay(BikeConstant.y_n_yes);
                            //自动扣款 单据状态为已完成
                            vehicleOrder.setBillStatus("4");
                            //添加消费记录
                            BikeMemberUserSpend bikeMemberUserSpend = new BikeMemberUserSpend();
                            bikeMemberUserSpend.setOrderId(vehicleOrder.getId());
                            bikeMemberUserSpend.setUserId(memberUser.getId());
                            bikeMemberUserSpend.setSpendAmount(bigDecimal);
                            bikeMemberUserSpend.setSpendType("1");
                            bikeMemberUserSpendMapper.insert(bikeMemberUserSpend);
                        }else {
                            //如果金额不为0 并为刷卡会员
                            //刷卡会员
                            if (vehicleOrder.getUseType().equals("2")){
                                //1.查询用户余额
                                if (memberUser.getBalance().compareTo(bigDecimal)>-1){
                                    //如果余额大于订单金额
                                    BigDecimal newBalance = memberUser.getBalance().subtract(bigDecimal);
                                    memberUser.setBalance(newBalance);
                                    bikeMemberUserMapper.updateById(memberUser);
                                    //修改订单记录
                                    //订单状态
                                    vehicleOrder.setRideStatus("5");
                                    //用车时长(分钟)
                                    vehicleOrder.setPayActual(bigDecimal);
                                    //是否支付
                                    vehicleOrder.setIsPay(BikeConstant.y_n_yes);
                                    //自动扣款 单据状态为已完成
                                    vehicleOrder.setBillStatus("4");
                                    //添加消费记录
                                    BikeMemberUserSpend bikeMemberUserSpend = new BikeMemberUserSpend();
                                    bikeMemberUserSpend.setOrderId(vehicleOrder.getId());
                                    bikeMemberUserSpend.setUserId(memberUser.getId());
                                    bikeMemberUserSpend.setSpendAmount(bigDecimal);
                                    bikeMemberUserSpend.setSpendType("1");
                                    bikeMemberUserSpendMapper.insert(bikeMemberUserSpend);
                                }else {
                                    //如果无法自动扣款，改为未支付
                                    vehicleOrder.setRideStatus("4");
                                    vehicleOrder.setIsPay(BikeConstant.y_n_no);
                                }
                            }else {
                                //非ic卡用户，不自动扣款，改为未支付
                                vehicleOrder.setRideStatus("4");
                                vehicleOrder.setIsPay(BikeConstant.y_n_no);
                            }
                        }

                    }
                }
                vehicleOrder.setPayCost(bigDecimal);
                bikeVehicleOrderMapper.updateById(vehicleOrder);
                this.lockSocketOpenYN(BikeConstant.y_n_yes,bikeStation.getCode(),bikePile.getCode(),bikePile.getCheckCode(),memberUser.getCode(),4);

            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 远程开关锁请求回调
     * userType 用户类型1:用户app2:员工app3:管理后台4:用户刷卡5:管理员刷卡
     * result  执行结果0：成功1：车辆编号识别失败2：开关执行失败
     * isLock  开关锁 0：关锁   1 ：开锁
     * */
    @Transactional(rollbackFor = Exception.class)
    public void switchLockReturn(SwitchLockRspRes switchLockRspRes) {
        List<String> result = switchLockRspRes.getResult();
        //获取网点信息
        BikeStation bikeStation = this.getStation(switchLockRspRes.getStationCode());
        //获取车桩信息
        BikePile bikePile = this.getBikePile(bikeStation, switchLockRspRes.getPileCode());
        //车辆信息
        BikeVehicle vehicle = this.getVehicleByPileId(bikePile.getId());
        // 会员卡用户
        BikeMemberUser memberUser = bikeMemberUserMapper.selectById(switchLockRspRes.getUserCode());

        if (result!=null&&result.isEmpty()){
            if (switchLockRspRes.getIsLock() == 1) {
                try {
                    //2.修改车辆信息
                    if (vehicle!=null){
                        if (switchLockRspRes.getUserType() == 1||switchLockRspRes.getUserType() == 4){
                            vehicle.setStatus(BikeConstant.bike_status_ride);
                            vehicle.setPileId("");
                            bikeVehicleMapper.updateById(vehicle);
                        }else {
                            vehicle.setStatus(BikeConstant.bike_status_repair);
                            vehicle.setPileId("");
                            bikeVehicleMapper.updateById(vehicle);
                        }
                    }
                    //开锁

                    // TODO: 2021/9/27  车桩状态测试时修改，正式删除
                    bikePile.setLockStatus("1");
                    bikePile.setPileStatus("1");
                    bikePile.setMemo("");
                    bikePileMapper.updateById(bikePile);
                    if (switchLockRspRes.getUserType() == 1) {
                        //会员信息
                        //1 会员app
                        //3.会员 新增借车记录
                        BikeVehicleOrder bikeVehicleOrder = new BikeVehicleOrder();
                        bikeVehicleOrder.setCode(RandomCodeUtils.getRandomCode(BikeConstant.vehicle_order_open));
                        bikeVehicleOrder.setVehicleId(vehicle.getId());
                        bikeVehicleOrder.setPickTime(new Date());
                        bikeVehicleOrder.setPickUser(memberUser.getId());
                        bikeVehicleOrder.setPickPile(bikePile.getId());
                        bikeVehicleOrder.setIsStop(BikeConstant.y_n_no);
                        bikeVehicleOrder.setUseType("1");
                        bikeVehicleOrder.setIsPay(BikeConstant.y_n_no);
                        bikeVehicleOrder.setRideStatus("1");
                        bikeVehicleOrder.setBillStatus("1");
                        bikeVehicleOrderMapper.insert(bikeVehicleOrder);
                        //5.发送websocket
                        this.lockSocketOpenYN(BikeConstant.y_n_yes, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), memberUser.getCode(), switchLockRspRes.getUserType());
                        //4.修改用户状态 暂无
                    } else if (switchLockRspRes.getUserType() == 2) {
                        //2 员工app
                        //管理员 新增管理员开关锁记录
                        BikePileLock bikePileLock = new BikePileLock();
                        bikePileLock.setCode(RandomCodeUtils.getRandomCode(BikeConstant.admin_order_open));
                        bikePileLock.setPickTime(new Date());
                        bikePileLock.setPickUser(switchLockRspRes.getUserCode());
                        bikePileLock.setPickPile(bikePile.getId());
                        bikePileLock.setUseType("1");
                        bikePileLock.setVehicleId(vehicle.getId());
                        bikePileLock.setVehicleStatus("1");
                        bikePileLockMapper.insert(bikePileLock);
                        //5.发送websocket
                        this.lockSocketOpenYN(BikeConstant.y_n_yes, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());

                    } else if (switchLockRspRes.getUserType() == 3) {
                        //3 管理后台
                        //管理员 新增管理员开关锁记录
                        BikePileLock bikePileLock = new BikePileLock();
                        bikePileLock.setCode(RandomCodeUtils.getRandomCode(BikeConstant.admin_order_open));
                        bikePileLock.setPickTime(new Date());
                        bikePileLock.setPickUser(switchLockRspRes.getUserCode());
                        bikePileLock.setPickPile(bikePile.getId());
                        bikePileLock.setUseType("3");
                        //判断是否有车

                        if (vehicle!=null&&StringUtils.isNotEmpty(vehicle.getId())) {
                            bikePileLock.setVehicleId(vehicle.getId());
                            bikePileLock.setVehicleStatus("1");
                        }
                        bikePileLockMapper.insert(bikePileLock);
                        this.lockSocketOpenYN(BikeConstant.y_n_yes, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());
                    } else if (switchLockRspRes.getUserType() == 4) {
                        //1 会员app
                        //3.会员 新增借车记录
                        BikeVehicleOrder bikeVehicleOrder = new BikeVehicleOrder();
                        bikeVehicleOrder.setCode(RandomCodeUtils.getRandomCode(BikeConstant.vehicle_order_open));
                        bikeVehicleOrder.setVehicleId(vehicle.getId());
                        bikeVehicleOrder.setPickTime(new Date());
                        bikeVehicleOrder.setPickUser(memberUser.getId());
                        bikeVehicleOrder.setPickPile(bikePile.getId());
                        bikeVehicleOrder.setIsStop(BikeConstant.y_n_no);
                        bikeVehicleOrder.setUseType("2");
                        bikeVehicleOrder.setIsPay(BikeConstant.y_n_no);
                        bikeVehicleOrder.setRideStatus("1");
                        bikeVehicleOrder.setBillStatus("1");
                        bikeVehicleOrderMapper.insert(bikeVehicleOrder);
                    } else if (switchLockRspRes.getUserType() == 5) {
                        //管理卡开锁
                        //管理员 新增管理员开关锁记录
                        BikePileLock bikePileLock = new BikePileLock();
                        bikePileLock.setCode(RandomCodeUtils.getRandomCode(BikeConstant.admin_order_open));
                        bikePileLock.setPickTime(new Date());
                        bikePileLock.setPickUser(switchLockRspRes.getUserCode());
                        bikePileLock.setPickPile(bikePile.getId());
                        bikePileLock.setUseType("2");
                        bikePileLock.setVehicleId(vehicle.getId());
                        bikePileLock.setVehicleStatus("1");
                        bikePileLockMapper.insert(bikePileLock);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (switchLockRspRes.getUserType() == 1) {
                        //会员信息
                        //1 会员app
                        this.lockSocketOpenYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), memberUser.getCode(), switchLockRspRes.getUserType());
                    } else  {
                        //2 管理
                        this.lockSocketOpenYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());
                    }
                }
            } else {
                try {
                    //关锁
                    if (StringUtils.isNotEmpty(String.valueOf(switchLockRspRes.getUserType()))){
                        if (switchLockRspRes.getUserType()==3){
                            bikePile.setLockStatus("0");
                            bikePile.setPileStatus("1");
                            bikePile.setMemo("");
                            bikePileMapper.updateById(bikePile);
                            if (vehicle!=null){
                                //修改车辆信息
                                vehicle.setStatus(BikeConstant.bike_status_pile);
                                vehicle.setPileId(bikePile.getId());
                                bikeVehicleMapper.updateById(vehicle);
                            }
                            this.lockSocketCloseYN(BikeConstant.y_n_yes, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    this.lockSocketCloseYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());
                }

            }
        } else {
            //失败
            if (result != null) {
                String memo = null;
                for (String tb : result) {
                    if (StringUtils.isEmpty(memo)) {
                        memo = tb;
                    } else {
                        memo = memo + "," + tb;
                    }
                }
                bikePile.setMemo(memo);
                bikePile.setPileStatus("0");
                bikePileMapper.updateById(bikePile);
            }
            if (switchLockRspRes.getIsLock() == 1){
                //回复开锁失败
                if (memberUser!=null){
                    this.lockSocketOpenYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), memberUser.getCode(), switchLockRspRes.getUserType());
                }else {
                    this.lockSocketOpenYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());
                }
            }else {
                //回复关锁失败
                if (memberUser!=null){
                    this.lockSocketCloseYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), memberUser.getCode(), switchLockRspRes.getUserType());
                }else {
                    this.lockSocketCloseYN(BikeConstant.y_n_no, bikeStation.getCode(), bikePile.getCode(), bikePile.getCheckCode(), switchLockRspRes.getUserCode(), switchLockRspRes.getUserType());
                }
            }
        }

    }
    //--------------------WebSocket-------------------------------
    public void lockSocketOpenYN(String YN, String stationCode, String pileCode, String checkCode, String openBy, int openType) {
        String Lock ;
        if (YN.equals(BikeConstant.y_n_yes)){
            Lock = "开锁成功";
        }else {
            Lock = "开锁失败";
        }
        //开锁类型(1会员2运维扫码开锁3后台开锁4通知还车成功)
        if (openType==4){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","payyes");
            jsonObject.put("msgTxt","payyes");//消息内容 y n
            userWebSocket.sendOneMessage(openBy,jsonObject.toString());
        }
        if (openType==3){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cmd","user");
            jsonObject.put("msgId",stationCode+pileCode+checkCode);
            jsonObject.put("msgTxt",stationCode+pileCode+checkCode+Lock);//消息内容 y n
            userWebSocket.sendOneMessage(openBy,jsonObject.toString());
        }
        if (openType==2){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",YN);
            jsonObject.put("msgTxt",Lock);//消息内容 y n
            userWebSocket.sendOneMessage(openBy,jsonObject.toString());
        }
        if (openType==1){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",YN);
            jsonObject.put("msgTxt",Lock);//消息内容 y n
            userWebSocket.sendOneMessage(openBy,jsonObject.toString());
        }

    }

    private void lockSocketCloseYN(String YN, String stationCode, String pileCode, String checkCode, String openBy, int openType) {
        String Lock ;
        if (YN.equals(BikeConstant.y_n_yes)){
            Lock = "关锁成功";
        }else {
            Lock = "关锁失败";
        }
        //开锁类型(1会员扫码开锁2运维扫码开锁3后台开锁)
        if (openType==3){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cmd","user");
            jsonObject.put("msgId",stationCode+pileCode+checkCode);
            jsonObject.put("msgTxt",stationCode+pileCode+checkCode+Lock);//消息内容 y n
            userWebSocket.sendOneMessage(openBy,jsonObject.toString());
        }
        if (openType==2){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cmd","user");
            jsonObject.put("msgId",stationCode+pileCode+checkCode);
            jsonObject.put("msgTxt",stationCode+pileCode+checkCode+Lock);//消息内容 y n
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userWebSocket.sendOneMessage(sysUser.getId(),jsonObject.toString());
        }
        if (openType==1){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cmd","user");
            jsonObject.put("msgId",stationCode+pileCode+checkCode);
            jsonObject.put("msgTxt",stationCode+pileCode+checkCode+Lock);//消息内容 y n
            userWebSocket.sendOneMessage(openBy,jsonObject.toString());
        }

    }

    /**
     * 上行关锁回调
     * */
    //----------------------------------------------------------------------------
    /**
     * 根据车辆id查订单
     * */
    private BikeVehicleOrder getOrderByBikeId(String id){
        QueryWrapper<BikeVehicleOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("vehicle_id",id);
        wrapper.isNull("park_time");
        wrapper.orderByDesc("pick_time");
        List<BikeVehicleOrder> bikeVehicleOrders = bikeVehicleOrderMapper.selectList(wrapper);
        if (bikeVehicleOrders.isEmpty()){
            return null;
        }else {
            return bikeVehicleOrders.get(0);
        }
    }
    /**
     * 根据车辆id查管理员开关锁记录
     * */
    private BikePileLock adminOrderByBikeId(String id) {
        QueryWrapper<BikePileLock> wrapper = new QueryWrapper<>();
        wrapper.eq("vehicle_id",id);
        wrapper.isNull("park_time");
        wrapper.orderByDesc("pick_time");
        List<BikePileLock> bikePileLockList = bikePileLockMapper.selectList(wrapper);


        BikePileLock bikePileLock = null;
        if(bikePileLockList != null && bikePileLockList.size() > 0){
            bikePileLock = bikePileLockList.get(0);
        }
        return bikePileLock;
    }
    /**
     * 添加骑行记录
     * */
    private void addVehicleOrder(BikeMemberUser memberUser, BikePile bikePile, BikeStation bikeStation, BikeVehicle vehicle) {
        BikeVehicleOrder bikeVehicleOrder = new BikeVehicleOrder();
        bikeVehicleOrder.setCode(RandomCodeUtils.getRandomCode(BikeConstant.vehicle_order_open));//code
        bikeVehicleOrder.setVehicleId(vehicle.getId());//车
        bikeVehicleOrder.setPickUser(memberUser.getId());//借车人
        bikeVehicleOrder.setPickTime(new Date());//借车时间
        bikeVehicleOrder.setPickPile(bikePile.getId());//借车桩
        bikeVehicleOrder.setIsStop(BikeConstant.y_n_no);//是否停止计费
        bikeVehicleOrder.setUseType(BikeConstant.use_type_scan);//1 扫码 2 刷卡
        bikeVehicleOrder.setRideStatus(BikeConstant.ride_status_scan);//骑行状态(1扫码骑行2刷卡骑行3停止计费4未支付5 未借车)
        bikeVehicleOrder.setIsPay(BikeConstant.y_n_no);//是否支付
        bikeVehicleOrderMapper.insert(bikeVehicleOrder);
    }
    /**
     * 添加管理员开锁记录
     */
    private void addBikePileLock(String orderBy,BikePile bikePile, BikeStation bikeStation, BikeVehicle vehicle){
        LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LoginRes::getUsername,orderBy);
        LoginRes loginRes = staffMapper.selectOne(queryWrapper);

        BikePileLock bikePileLock = new BikePileLock();
        bikePileLock.setCode(RandomCodeUtils.getRandomCode(BikeConstant.vehicle_order_open));
        bikePileLock.setPickTime(new Date());
        bikePileLock.setPickUser(loginRes.getId());
        bikePileLock.setPickPile(bikePile.getId());
        bikePileLock.setUseType("1");
        bikePileLock.setVehicleId(vehicle.getId());
        bikePileLock.setVehicleStatus("1");
        bikePileLockMapper.insert(bikePileLock);
    }

    /**
     获取用户未支付订单
     */
    private BikeVehicleOrder getMemberOrderByUserId(String id) {
        QueryWrapper<BikeVehicleOrder> bikeVehicleOrderWrapper = new QueryWrapper<>();
        bikeVehicleOrderWrapper.eq("pick_user",id);
        bikeVehicleOrderWrapper.ne("is_pay",BikeConstant.y_n_no);
        return bikeVehicleOrderMapper.selectOne(bikeVehicleOrderWrapper);
    }
    /**
     * pileId获取车辆信息
     * */
    private BikeVehicle getVehicleByPileId(String id) {
        QueryWrapper<BikeVehicle> vehicleWrapper = new QueryWrapper<>();
        vehicleWrapper.eq("pile_id",id);
        return bikeVehicleMapper.selectOne(vehicleWrapper);
    }
    /**
     * code获取车辆信息
     * */
    private BikeVehicle getVehicleByCode(String vehicleCode) {
        QueryWrapper<BikeVehicle> vehicleWrapper = new QueryWrapper<>();
        vehicleWrapper.eq("code",vehicleCode);
        return bikeVehicleMapper.selectOne(vehicleWrapper);
    }
    /**
     * code获取会员信息
     * */
    private BikeMemberUser getMemberUser(String memberCode) {
        QueryWrapper<BikeMemberUser> memberWrapper = new QueryWrapper<>();
        memberWrapper.eq("code",memberCode);
        return bikeMemberUserMapper.selectOne(memberWrapper);
    }
    /**
     * ic卡 获取会员信息
     * */
    private BikeMemberUser getMemberUserByCard(String openBy) {
        QueryWrapper<BikeMemberUserCard> wrapper = new QueryWrapper<>();
        wrapper.eq("code",openBy);
        BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectOne(wrapper);
        return bikeMemberUserMapper.selectById(userCard.getUserId());
    }

    /**
     * 获取车桩
     * */
    public BikePile getBikePile(BikeStation bikeStation, String pileCode) {
        QueryWrapper<BikePile> bikePileQueryWrapper = new QueryWrapper<>();
        bikePileQueryWrapper.eq("station_id",bikeStation.getId());
        bikePileQueryWrapper.eq("code",pileCode);
        return bikePileMapper.selectOne(bikePileQueryWrapper);
    }

    /**
     * 获取网点
     * */
    public BikeStation getStation(String stationCode) {
        QueryWrapper<BikeStation> wrapper = new QueryWrapper<>();
        wrapper.eq("code",stationCode);
        return  bikeStationMapper.selectOne(wrapper);
    }

    //-----------------------------------------车桩默认语音
    /**
     * 车桩默认语音回调
     * pickVoice 借车成功语音  , returnVoice还车成功语音,errorVoice异常语音,volumeSize音量
     */
    public void setVoiceReturn(String stationCode, String pileCode, String pickVoice, String returnVoice, String errorVoice, int volumeSize) {
        // 查询网点
        BikeStation station = getStation(stationCode);
        if(station == null){
            Log.error("车桩语音回调，网点不存在");
            return;
        }
        // 转换车桩编号
        Integer pileInt = Integer.valueOf(pileCode);
        if(pileInt<10){
            pileCode = "0" + pileInt.toString();
        }
        // 查询车桩
        BikePile bikePile = getBikePile(station, pileCode);
        if(bikePile == null){
            Log.error("车桩语音回调，车桩不存在");
            return;
        }
        bikePile.setPickVoice(pickVoice);
        bikePile.setReturnVoice(returnVoice);
        bikePile.setErrorVoice(errorVoice);
        bikePile.setVolumeSize(volumeSize);
        bikePileMapper.updateById(bikePile);
    }



    //------------------------------队列方法-------------------------------------------
    //
    ///**
    // * 上行开锁校验 1成功
    // * */
    //public int upOpenRequestDevice(String stationCode, String pileCode, String checkCode, String vehicleCode, String openBy, int openType) {
    //    //获取网点信息
    //    BikeStation bikeStation = this.getStation(stationCode);
    //    //获取车桩信息
    //    BikePile bikePile=this.getBikePile(bikeStation,pileCode,checkCode);
    //    //车辆信息
    //    BikeVehicle vehicle =this.getVehicleByPileId(bikePile.getId());
    //    //判断车桩上得code和车辆code是否一致
    //    if (!vehicle.getCode().equals(vehicleCode)){
    //        return 0;
    //    }
    //    //判断车桩存在
    //    if (bikePile==null){
    //        return 0;
    //    }else {
    //        //判断车桩各个状态
    //        if (bikePile.getIsLock().equals(BikeConstant.y_n_yes)){
    //            return 0;
    //        }
    //        if (bikePile.getPileStatus().equals("0")){
    //            //车桩状态(1正常0异常)
    //            return 0;
    //        }
    //        if (bikePile.getStatus().equals("0")){
    //            //状态(1启用0禁用)
    //            return 0;
    //        }
    //        if (bikePile.getIsRegister()==0){
    //            //0 否 1 是   0 未注册
    //            return 0;
    //        }
    //        if (bikePile.getLockStatus().equals("1")){
    //            //(1开0关) 开就是无车，关就是有车
    //            return 0;
    //        }
    //    }
    //    //如果是会员开锁
    //    if (openType==1){
    //        //判断车桩车状态
    //        if (vehicle.getIsRegister().equals(BikeConstant.y_n_no)){
    //            return 0;
    //        }
    //        //通过code 获取用户信息
    //        BikeMemberUser memberUser = this.getMemberUserByCard(openBy);
    //        if (memberUser!=null){
    //            if (!memberUser.getStatus().equals(BikeConstant.member_status_normal)){
    //                //判断用户状态是否非正常
    //                return 0;
    //            }
    //        }else {
    //            return 0;
    //        }
    //        //获取用户订单 判断是否都已还车
    //        BikeVehicleOrder bikeVehicleOrder=this.getMemberOrderByUserId(memberUser.getId());
    //        if (bikeVehicleOrder!=null){
    //            //如果查询到，表示有订单是未支付
    //            return 0;
    //        }
    //    }
    //
    //    //1为可开锁，0为不可开始
    //    return 1;
    //}
    //
    //
    //
    ///**
    // * 下发关锁请求校验 0成功  只有后台
    // * */
    //public String downCloseDevice(String stationCode, String pileCode, String checkCode, String closeBy, int closeType) {
    //    //获取网点信息
    //    BikeStation bikeStation = this.getStation(stationCode);
    //    //获取车桩信息
    //    BikePile bikePile=this.getBikePile(bikeStation,pileCode,checkCode);
    //    //判断车桩存在
    //    if (bikePile==null){
    //        return "车桩已存在";
    //    }else {
    //        //判断车桩各个状态
    //        if (bikePile.getIsLock().equals(BikeConstant.y_n_yes)){
    //            return "车桩已锁定";
    //        }
    //        if (bikePile.getStatus().equals("0")){
    //            //车桩状态(1正常0异常)
    //            return "车桩异常";
    //        }
    //        if (bikePile.getStatus().equals("0")){
    //            //状态(1启用0禁用)
    //            return "车桩禁用";
    //        }
    //        if (bikePile.getIsRegister().equals("")){
    //            //0 否 1 是   0 未注册
    //            return "车桩未注册";
    //        }
    //        if (bikePile.getLockStatus().equals("10")){
    //            //(1开0关) 开就是无车，关就是有车
    //            return "车桩不可以";
    //        }
    //        return "0";
    //    }
    //}
    ///**
    // * 上行关锁请求校验 0成功
    // * */
    //public int upCloseDevice(String stationCode, String pileCode, String checkCode, String vehicleCode, Date closeTime) {
    //    //获取网点信息
    //    BikeStation bikeStation = this.getStation(stationCode);
    //    //获取车桩信息
    //    BikePile bikePile=this.getBikePile(bikeStation,pileCode,checkCode);
    //    //判断车桩存在
    //    if (bikePile==null){
    //        return 1;
    //    }else{
    //        //判断车桩各个状态
    //        if (bikePile.getIsLock().equals(BikeConstant.y_n_yes)){
    //            return 1;
    //        }
    //        if (bikePile.getStatus().equals("0")){
    //            //车桩状态(1正常0异常)
    //            return 1;
    //        }
    //        if (bikePile.getStatus().equals("0")){
    //            //状态(1启用0禁用)
    //            return 1;
    //        }
    //        if (bikePile.getIsRegister()==0){
    //            //0 否 1 是   0 未注册
    //            return 1;
    //        }
    //        if (bikePile.getLockStatus().equals("10")){
    //            //(1开0关) 开就是无车，关就是有车
    //            return 1;
    //        }
    //        return 0;
    //    }
    //}


    //--------------------------------------------------------------------------------
    ///**
    // * 下发开锁回调
    // * */
    //public void downOpenDeviceReturn(String stationCode, String pileCode, String checkCode, String openBy, int openType , int isOpen) {
    //    //获取网点信息
    //    BikeStation bikeStation = this.getStation(stationCode);
    //    //获取车桩信息
    //    BikePile bikePile=this.getBikePile(bikeStation,pileCode);
    //    //车辆信息
    //    BikeVehicle vehicle =this.getVehicleByPileId(bikePile.getId());
    //    if (isOpen==1){
    //        //设置桩位为开锁
    //        bikePile.setIsLock(BikeConstant.lock_yes);
    //        bikePileMapper.updateById(bikePile);
    //
    //        //会员扫码
    //        if (openType==1){
    //            //获取扫码会员信息
    //            BikeMemberUser memberUser =this.getMemberUser(openBy);
    //            if (vehicle!=null){
    //                //单车状态
    //                vehicle.setStatus(BikeConstant.bike_status_pile);
    //                //添加骑行借车记录
    //                this.addVehicleOrder(memberUser,bikePile,bikeStation,vehicle);
    //            }
    //        }
    //        //运维扫码
    //        if (openType==2){
    //            if (vehicle!=null){
    //                vehicle.setStatus(BikeConstant.bike_status_fault);
    //                //添加骑行借车记录
    //                this.addBikePileLock(openBy,bikePile,bikeStation,vehicle);
    //
    //            }
    //        }
    //        //后台开锁
    //        if (openType==3){
    //            vehicle.setStatus(BikeConstant.bike_status_fault);
    //        }
    //        bikeVehicleMapper.updateById(vehicle);
    //    }else {
    //        //不开锁
    //    }
    //    //WebSocket
    //    if (isOpen==1){
    //        this.lockSocketOpenYN(BikeConstant.y_n_yes,stationCode,pileCode,checkCode,openBy,openType);
    //    }else {
    //        this.lockSocketOpenYN(BikeConstant.y_n_no,stationCode,pileCode,checkCode,openBy,openType);
    //    }
    //}
    ///**
    // * 下发关锁回调  只有后台
    // * */
    //public void downCloseDeviceReturn(String stationCode, String pileCode, String checkCode, String vehicleCode, String closeBy, Date closeTime, int closeType, int isClose) {
    //    //获取网点信息
    //    BikeStation bikeStation = this.getStation(stationCode);
    //    //获取车桩信息
    //    BikePile bikePile=this.getBikePile(bikeStation,pileCode);
    //    if (isClose==1) {
    //        //设置桩位为开锁
    //        bikePile.setIsLock(BikeConstant.lock_yes);
    //        bikePileMapper.updateById(bikePile);
    //        this.lockSocketCloseYN(BikeConstant.y_n_yes,stationCode,pileCode,checkCode,closeBy,3);
    //    }else {
    //        this.lockSocketCloseYN(BikeConstant.y_n_no,stationCode,pileCode,checkCode,closeBy,3);
    //        //不开锁
    //    }
    //}
    //
    ///**
    // * 上行开锁回调   1会员卡 2 管理卡
    // * */
    //public void upOpenDevice(String stationCode, String pileCode, String vehicleCode, String checkCode, int isOpen, int openType, Date openTime, String openBy) {
    //    //获取网点信息
    //    BikeStation bikeStation = this.getStation(stationCode);
    //    //获取车桩信息
    //    BikePile bikePile=this.getBikePile(bikeStation,pileCode);
    //    //车辆信息
    //    BikeVehicle vehicle =this.getVehicleByPileId(bikePile.getId());
    //    if (isOpen==1){
    //        //设置桩位为开锁
    //        bikePile.setIsLock(BikeConstant.lock_yes);
    //        bikePileMapper.updateById(bikePile);
    //        //会员卡
    //        if (openType==1){
    //            //获取扫码会员信息
    //            BikeMemberUser memberUser =this.getMemberUserByCard(openBy);
    //            if (vehicle!=null){
    //                //单车状态
    //                vehicle.setStatus(BikeConstant.bike_status_pile);
    //                //添加骑行借车记录
    //                this.addVehicleOrder(memberUser,bikePile,bikeStation,vehicle);
    //            }
    //        }
    //        //管理卡
    //        if (openType==2){
    //            if (vehicle!=null){
    //                vehicle.setStatus(BikeConstant.bike_status_fault);
    //            }
    //        }
    //        bikeVehicleMapper.updateById(vehicle);
    //    }else {
    //        //不开锁
    //    }
    //}
}
